﻿using AuthorizationApiSample.Data.Entities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace AuthorizationApiSample.Data
{
    public class ApplicationDbContext : IdentityDbContext<UserEntity, RoleEntity, string>
    {
        public ApplicationDbContext(DbContextOptions options)
            : base(options)
        {
            base.Database.EnsureCreated();//自动创建数据库
        }

        #region Tables

        public DbSet<PermissionsEntity> Permissions { get; set; }

        public DbSet<RolePermissionsEntity> RolePermissions { get; set; }

        #endregion

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<RoleEntity>(b =>
            {
                b.HasMany<RolePermissionsEntity>().WithOne().HasForeignKey(rp => rp.RoleId).IsRequired();
            });

            builder.Entity<PermissionsEntity>(b =>
            {
                b.HasKey(p => p.Id);
                b.ToTable("AspNetPermissions");
                b.Property(p => p.ConcurrencyStamp).IsConcurrencyToken();
                b.Property(p => p.Name).HasMaxLength(256);
                b.Property(p => p.ControllerName).HasMaxLength(256);
                b.Property(p => p.ControllerName).HasMaxLength(256);

                b.HasMany<RolePermissionsEntity>().WithOne().HasForeignKey(rp => rp.PermissionsId).IsRequired();
            });

            builder.Entity<RolePermissionsEntity>(b =>
            {
                b.HasKey(r => new { r.PermissionsId, r.RoleId });
                b.ToTable("AspNetRolePermissions");
            });
        }

        //初始化数据，反射获取 ControllerBase 的子类，并且判断是否 Authorize 和 AllowAnonymous 特性

    }
}
